package org.xussen.dic;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class TreeUtil {

	public static Node addLibrary(Set<String> keyWords) {
		Iterator<String> it = keyWords.iterator();
		Node head = new Node('h', 0, null);
		Node node = head; 
		String keyword = null ;
		while (it.hasNext()) {
			boolean isWords;
			boolean hasNext;
			keyword = it.next() ;
			char[] chars = keyword.toCharArray();
			for (int i = 0; i < chars.length; i++) {
				if (chars.length == (i + 1)) {
					isWords = true;
					hasNext = false;
				} else {
					isWords = false;
					hasNext = true;
				}
				int status = 1;
				if (isWords && hasNext) {
					status = 2;
				}
				if (!isWords && hasNext) {
					status = 1;
				}
				if (isWords && !hasNext) {
					status = 3;
				}
				node.add(new Node(chars[i], status, new String(chars,0,i+1)));
				node = node.get(chars[i]);
			}
			node = head;
		}
		return head;
	}

	/**
	 * 遍历树，获取排好序的节点列表
	 * @param all
	 * @param begin
	 * @param end
	 * @return
	 */
	public static List<Node> treeToLibrary(List<Node> all, int begin, int end) {
		int beginNext = end;
		for (int i = begin; i < end; i++) {
			Node[] branches = all.get(i).branches;
//			Arrays.sort(branches, ChildrenNumComparator.instance);
			for (int j = 0; j < branches.length; j++) {
				all.add(branches[j]);
			}
		}
		int endNext = all.size();
		if (begin != end) {
			treeToLibrary(all, beginNext, endNext);
		}
		return all;
	}
	
}
